<template>
  <div
    ref="canvasContainerRef" 
    :class="['canvas-container', { 'grid-visible': gridVisible }]"
    @dragover.prevent
    @drop="handleDrop" 
    @click="handleCanvasClick"
  >
    <div
      class="canvas-content"
      ref="canvasContentRef"
      @dragover.prevent
      @click.stop="selectCanvas" 
      :data-component-id="'canvas'"
      :class="{ 'selected': designStore.selectedComponentId === 'canvas' }"
    >
      <!-- 使用 DynamicRenderer 渲染放置的组件 -->
      <DynamicRenderer
        v-for="component in designStore.canvasComponents"
        :key="component.id"
        :component="component"
      />

      <!-- 调整大小的句柄容器 -->
      <div
        v-if="designStore.selectedComponent && designStore.selectedComponentId !== 'canvas'" 
        class="resize-handles-container"
        :style="selectedComponentHandlesStyle"
      >
        <ResizeHandle
          v-for="dir in handleDirections"
          :key="dir"
          :direction="dir"
          :isForInteractiveComponent="isSelectedComponentInteractive"
          @resize-start="(customEventData) => { 
              console.log('[CanvasArea @resize-start] Received custom data:', customEventData);
              handleResizeStart(customEventData); // Pass the custom object directly
          }" 
        />
      </div>
      
      <!-- 画布调整大小的句柄容器 -->
      <div
        v-if="designStore.selectedComponentId === 'canvas'" 
        class="canvas-resize-handles-container"
      >
        <ResizeHandle
          v-for="dir in handleDirections"
          :key="dir"
          :direction="dir"
          :isForInteractiveComponent="true"
          @resize-start="(customEventData) => { 
              console.log('[CanvasArea @canvas-resize-start] Received custom data:', customEventData);
              handleCanvasResizeStart(customEventData);
          }" 
        />
      </div>

      <!-- 实时尺寸指示器 -->
      <div 
        v-if="resizingState && designStore.selectedComponentId !== 'canvas'"
        class="size-indicator"
      >
        {{ Math.round(newWidth) }} × {{ Math.round(newHeight) }} px
      </div>
      
      <!-- 画布尺寸指示器 -->
      <div 
        v-if="canvasResizingState"
        class="size-indicator canvas-size-indicator"
      >
        画布: {{ Math.round(designStore.canvasSize.width) }} × {{ Math.round(designStore.canvasSize.height) }} px
      </div>

      <p v-if="designStore.canvasComponents.length === 0">将左侧组件拖拽到此处</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed, watch, provide } from 'vue';
import { v4 as uuidv4 } from 'uuid'; // 用于生成唯一 ID
import DynamicRenderer from './DynamicRenderer.vue'; // 引入渲染器组件
import ResizeHandle from './ResizeHandle.vue'; // 引入句柄组件
import { useDesignStore, type CanvasComponent, isContainerType } from '../stores/designStore'; // 重新导入类型
import componentManager from '../services/ComponentManagerService'; // 使用组件管理服务替代直接导入

const designStore = useDesignStore();

const gridVisible = ref(true);
// 从 store 获取 gridSize
const gridSize = computed(() => designStore.gridSize);

const handleKeyDown = (event: KeyboardEvent) => {
    const targetElement = event.target as HTMLElement;

    // Toggle Grid
    if (event.ctrlKey && event.key === 'g') {
        event.preventDefault();
        gridVisible.value = !gridVisible.value;
        return;
    }

    // Delete Component
    if ((event.key === 'Delete' || event.key === 'Backspace') && designStore.selectedComponentId) {
        const targetTagName = targetElement.tagName.toLowerCase();
        const isInput = targetTagName === 'input' || targetTagName === 'textarea';
        const isContentEditable = targetElement.isContentEditable;

        if (isInput || isContentEditable) {
            console.log('Keydown Delete/Backspace ignored: Event target is input/textarea or contenteditable.');
            return; // 如果是输入控件或可编辑元素，则不执行删除
        }

        // 如果不是输入控件，则执行删除
        console.log(`画布 KeyDown: ${event.key} pressed, deleting ${designStore.selectedComponentId}`); // ++ Log
        event.preventDefault(); 
        designStore.deleteComponent(designStore.selectedComponentId);
        return; 
    }

    // Undo (Ctrl+Z)
    if (event.ctrlKey && event.key === 'z') {
        event.preventDefault();
        console.log('画布：检测到 Ctrl+Z，执行撤销...');
        designStore.undo();
        return;
    }

    // Redo (Ctrl+Y or Ctrl+Shift+Z)
    if ((event.ctrlKey && event.key === 'y') || (event.ctrlKey && event.shiftKey && event.key === 'z')) {
        event.preventDefault();
        console.log('画布：检测到 Ctrl+Y/Ctrl+Shift+Z，执行重做...');
        designStore.redo();
        return;
    }

    // Copy (Ctrl+C)
    if (event.ctrlKey && event.key === 'c' && designStore.selectedComponentId) {
        const targetTagName = targetElement.tagName.toLowerCase();
        const isInput = targetTagName === 'input' || targetTagName === 'textarea';
        const isContentEditable = targetElement.isContentEditable;

        if (isInput || isContentEditable) {
            console.log('Keydown Ctrl+C ignored: Event target is input/textarea or contenteditable.');
            return; // 如果是输入控件或可编辑元素，则不执行复制
        }

        event.preventDefault();
        console.log(`画布：检测到 Ctrl+C，复制组件 ${designStore.selectedComponentId}...`);
        designStore.copyComponent(designStore.selectedComponentId);
        return;
    }

    // Paste (Ctrl+V)
    if (event.ctrlKey && event.key === 'v') {
        const targetTagName = targetElement.tagName.toLowerCase();
        const isInput = targetTagName === 'input' || targetTagName === 'textarea';
        const isContentEditable = targetElement.isContentEditable;

        if (isInput || isContentEditable) {
            console.log('Keydown Ctrl+V ignored: Event target is input/textarea or contenteditable.');
            return; // 如果是输入控件或可编辑元素，则不执行粘贴
        }

        event.preventDefault();
        console.log('画布：检测到 Ctrl+V，执行粘贴...');
        // 使用默认偏移量粘贴组件
        designStore.pasteComponent();
        return;
    }
};

onMounted(() => {
    window.addEventListener('keydown', handleKeyDown); // Add combined listener

    console.log('[CanvasArea onMounted] Hook execution finished.'); // 修改日志文本以区分

    // 初始化时应用画布尺寸
    updateCanvasStyle();
    
    // 监听画布尺寸变化
    watch(() => designStore.canvasSize, () => {
        updateCanvasStyle();
    }, { deep: true });
    
    // 确保画布背景元素样式已应用
    if (canvasContentRef.value) {
        canvasContentRef.value.style.backgroundColor = '#ffffff';
        canvasContentRef.value.style.borderRadius = '4px';
        canvasContentRef.value.style.border = '1px solid #cccccc';
        canvasContentRef.value.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.1)';
        console.log('[CanvasArea onMounted] 应用画布样式');
    }
});

onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
    // ... (resize listener cleanup remains the same)
    window.removeEventListener('mousemove', handleResizing);
    window.removeEventListener('mouseup', handleResizeEnd);
    // 清理画布大小调整的事件监听
    window.removeEventListener('mousemove', handleCanvasResizing);
    window.removeEventListener('mouseup', handleCanvasResizeEnd);
});

// 存储画布上的组件列表
const canvasComponents = ref<CanvasComponent[]>([]);
const canvasContainerRef = ref<HTMLElement | null>(null); // <-- Add ref for the container
const canvasContentRef = ref<HTMLElement | null>(null);

// 定义选中状态
const selectedComponentId = ref<string | null>(null);

const selectedComponent = computed(() => {
  if (!selectedComponentId.value) return null;
  return canvasComponents.value.find(c => c.id === selectedComponentId.value) || null;
});

// --- 辅助函数：解析像素值 (确保在使用前定义) ---
const parsePx = (value: string | undefined | number): number => {
  if (typeof value === 'number') return value;
  if (typeof value === 'string' && value.endsWith('px')) {
    return parseFloat(value.slice(0, -2)) || 0;
  }
  return 0; 
};

// --- 辅助函数：计算组件相对于画布的绝对位置 ---
const getComponentAbsolutePosition = (componentId: string): { left: number; top: number } | null => {
  // ++ Log start of calculation ++
  console.log(`[getAbsPos] Calculating absolute position for: ${componentId}`);
  const component = designStore.findComponentById(designStore.canvasComponents, componentId);
  if (!component) {
      console.warn(`[getAbsPos] Component ${componentId} not found!`);
      return null;
  }

  const componentLeftRaw = component.style?.left;
  const componentTopRaw = component.style?.top;
  const componentLeft = parsePx(componentLeftRaw);
  const componentTop = parsePx(componentTopRaw);
  // ++ Log parsed local coords ++
  console.log(`[getAbsPos] Component ${componentId} - Parsed local style: left=${componentLeft}, top=${componentTop}`);

  const parent = designStore.findParentComponent(designStore.canvasComponents, componentId);
  if (!parent) {
    // Root component
    console.log(`[getAbsPos] Component ${componentId} is root. Returning absolute position: { left: ${componentLeft}, top: ${componentTop} }`);
    return { left: componentLeft, top: componentTop };
  } else {
    // Nested component
    // ++ Log parent found ++
    console.log(`[getAbsPos] Component ${componentId} has parent: ${parent.id}. Recursively getting parent position...`);
    const parentPosition = getComponentAbsolutePosition(parent.id);
    if (parentPosition) {
      // ++ Log parent position ++
      console.log(`[getAbsPos] Parent ${parent.id} absolute position:`, parentPosition);
      const finalLeft = parentPosition.left + componentLeft;
      const finalTop = parentPosition.top + componentTop;
      // ++ Log final calculated position ++
      console.log(`[getAbsPos] Component ${componentId} calculated final absolute position: { left: ${finalLeft}, top: ${finalTop} } (parent.left + child.left, parent.top + child.top)`);
      return { left: finalLeft, top: finalTop };
    } else {
      // ++ Log failure to get parent position ++
      console.warn(`[getAbsPos] Failed to calculate parent (${parent.id}) position for child ${componentId}. Returning null.`);
      return null;
    }
  }
};

// --- 创建 handlesStyle ref --- 
const handlesStyle = ref<Record<string, string>>({
  position: 'absolute',
  left: '0px',
  top: '0px',
  width: '0px',
  height: '0px',
  display: 'none',
  pointerEvents: 'none',
});

// --- 创建 watcher 监听 selectedComponent --- 
watch(() => designStore.selectedComponent, async (newComponent) => {
  console.log('[Watcher selectedComponent] Detected change. New component:', newComponent ? newComponent.id : 'None');
  console.log(`[Watcher selectedComponent] Current isDraggingComponent state: ${designStore.isDraggingComponent}`);

  if (newComponent) {
    // ++ Log before getting position ++
    console.log(`[Watcher selectedComponent] Calculating position for selected component ${newComponent.id}...`);
    const position = getComponentAbsolutePosition(newComponent.id);
    const rawWidth = newComponent.style?.width;
    const rawHeight = newComponent.style?.height;
    // ++ Log raw style and calculated position ++
    console.log(`[Watcher selectedComponent] Component ${newComponent.id} raw style: width=${rawWidth}, height=${rawHeight}`);
    console.log(`[Watcher selectedComponent] Calculated absolute position for handles:`, position);

    if (position) {
      const isValidPixelValue = (value: string | number | undefined): boolean =>
          typeof value === 'string' && value.endsWith('px') && !isNaN(parseFloat(value));

      // Check if we need to use the DOM to get the actual dimensions
      let finalWidth = isValidPixelValue(rawWidth) ? rawWidth as string : '';
      let finalHeight = isValidPixelValue(rawHeight) ? rawHeight as string : '';
      
      // If dimensions from style are missing, try to get them from DOM
      if (!finalWidth || !finalHeight) {
        // Wait for next tick to ensure component is rendered
        await nextTick();
        
        // Try to get the element from DOM
        const componentElement = document.querySelector(`[data-component-id="${newComponent.id}"]`) as HTMLElement;
        
        if (componentElement) {
          const rect = componentElement.getBoundingClientRect();
          console.log(`[Watcher selectedComponent] Got dimensions from DOM for ${newComponent.id}:`, rect);
          
          if (!finalWidth && rect.width > 0) {
            finalWidth = `${rect.width}px`;
          }
          
          if (!finalHeight && rect.height > 0) {
            finalHeight = `${rect.height}px`;
          }
        }
      }
      
      // Final fallback for width/height
      finalWidth = finalWidth || '100px';  // Default from propertyPanelConfig
      finalHeight = finalHeight || '32px'; // Default from propertyPanelConfig
      
      console.log(`[Watcher selectedComponent] Final dimensions for ${newComponent.id}: width=${finalWidth}, height=${finalHeight}`);

      handlesStyle.value = {
        position: 'absolute',
        left: `${position.left}px`,
        top: `${position.top}px`,
        width: finalWidth,
        height: finalHeight,
        display: 'block',
        pointerEvents: 'none',
      };
      // ++ Log the style being applied ++
      console.log(`[Watcher selectedComponent] Updating handlesStyle to:`, JSON.parse(JSON.stringify(handlesStyle.value)));
    } else {
      console.warn(`[Watcher selectedComponent] Position calculation failed for ${newComponent.id}. Hiding handles.`);
      handlesStyle.value.display = 'none'; // Hide if position invalid
    }
  } else {
    // No component selected, hide handles
    handlesStyle.value.display = 'none';
    console.log('[Watcher selectedComponent] No component selected. Hiding handles.');
  }
}, { deep: true, immediate: true });

const selectComponent = (id: string) => {
  designStore.selectComponent(id);
};

const deselectComponent = () => {
  designStore.selectComponent(null);
};

// New handler for canvas clicks
const handleCanvasClick = (event: MouseEvent) => {
  // Check if the click target is the canvas container itself or the canvas content area
  const containerClicked = event.target === canvasContainerRef.value;
  const contentClickedDirectly = event.target === canvasContentRef.value;
  
  // Additionally, check if the click target is INSIDE a rendered component
  const targetElement = event.target as HTMLElement;
  const clickedInsideComponent = targetElement.closest('.rendered-component');

  console.log(`[CanvasArea handleCanvasClick] Target:`, targetElement);
  console.log(`[CanvasArea handleCanvasClick] Clicked container: ${containerClicked}, Clicked content directly: ${contentClickedDirectly}, Clicked inside component element: ${!!clickedInsideComponent}`);

  // Only deselect if the click was truly on the background 
  // (either the container, the content div directly, or not inside any component)
  if (containerClicked || contentClickedDirectly || !clickedInsideComponent) {
      console.log('[CanvasArea handleCanvasClick] Deselecting component.');
      deselectComponent();
  } else {
      console.log('[CanvasArea handleCanvasClick] Clicked inside a component, not deselecting.');
      // If the click was inside a component, the DynamicRenderer's handleClick should handle selection.
  }
};

// --- 辅助函数：设置组件尺寸的函数 ---
const setComponentSize = (newComponentBase, componentName) => {
  if (!componentName) {
    // 没有组件名称时的默认尺寸
    newComponentBase.style.width = '300px';
    newComponentBase.style.height = '200px';
    console.log(`[DropAddOnCanvas] 未知组件类型，使用默认尺寸 300x200`);
    return;
  }

  // 特殊调试tag组件
  if (componentName === 'tag') {
    console.log('>>> 发现Tag组件，开始详细调试 <<<');
    console.log('组件管理服务状态:', componentManager);
    console.log('组件配置:', componentManager.getComponentConfig(componentName));
    console.log('defaultSize属性:', componentManager.getComponentConfig(componentName)?.defaultSize);
  }

  try {
    // 从组件管理服务获取组件配置
    const componentConfig = componentManager.getComponentConfig(componentName);
    console.log(`[DropAddOnCanvas] 获取到组件 ${componentName} 的配置:`, componentConfig);
    
    // 特别标记tag组件处理过程
    if (componentName === 'tag') {
      console.log('>>> Tag组件配置检查 <<<');
      console.log('配置是否存在:', !!componentConfig);
      console.log('defaultSize是否存在:', !!(componentConfig && componentConfig.defaultSize));
      console.log('width是否存在:', !!(componentConfig && componentConfig.defaultSize && componentConfig.defaultSize.width));
      console.log('height是否存在:', !!(componentConfig && componentConfig.defaultSize && componentConfig.defaultSize.height));
      console.log('最终宽度值:', componentConfig?.defaultSize?.width);
      console.log('最终高度值:', componentConfig?.defaultSize?.height);
    }
    
    // 检查组件配置中是否有默认尺寸，并且尺寸有效
    if (componentConfig && 
        componentConfig.defaultSize && 
        componentConfig.defaultSize.width && 
        componentConfig.defaultSize.height) {
        
      // 应用配置中的默认尺寸
      const defaultWidth = componentConfig.defaultSize.width;
      const defaultHeight = componentConfig.defaultSize.height;
      
      newComponentBase.style.width = `${defaultWidth}px`;
      newComponentBase.style.height = `${defaultHeight}px`;
      console.log(`[DropAddOnCanvas] 应用配置的默认尺寸: ${componentName} = ${defaultWidth}x${defaultHeight}`);
    } else {
      // 配置中没有有效的默认尺寸，统一使用300x200
      console.log(`[DropAddOnCanvas] 组件 ${componentName} 没有有效的默认尺寸配置，使用统一默认值 300x200`);
      
      // 不再判断组件类型，统一使用300x200
      newComponentBase.style.width = '300px';
      newComponentBase.style.height = '200px';
    }
  } catch (error) {
    // 发生错误时使用安全的默认值
    console.warn(`[DropAddOnCanvas] 获取组件配置时出错:`, error);
    newComponentBase.style.width = '300px';
    newComponentBase.style.height = '200px';
  }
};

// 处理放置事件
const handleDrop = (event: DragEvent) => {
  console.log('[handleDrop-Canvas] Canvas root received drop event');
  event.preventDefault(); // 阻止默认行为
  const dragDataString = event.dataTransfer?.getData('application/json');
  if (!dragDataString) {
      console.warn('[handleDrop-Canvas] Failed to get dataTransfer data');
      return;
  }

  try {
    const dragData = JSON.parse(dragDataString);
    console.log('[handleDrop-Canvas] Parsed drag data:', dragData);

    // 获取画布内容区域的引用和边界
    const canvasContentEl = canvasContentRef.value;
    if (!canvasContentEl) {
        console.warn('[handleDrop-Canvas] Canvas content ref not found!');
        return;
    }
    const canvasRect = canvasContentEl.getBoundingClientRect();

    // 计算放置点相对于画布内容区域的坐标 (考虑滚动)
    const dropX = event.clientX - canvasRect.left + canvasContentEl.scrollLeft;
    const dropY = event.clientY - canvasRect.top + canvasContentEl.scrollTop;
    const currentGridSize = designStore.gridSize;

    // --- 处理移动现有组件 --- 
    if (dragData.action === 'move') {
        const movedComponentId = dragData.id;
        const componentToMove = designStore.findComponentById(designStore.canvasComponents, movedComponentId);
        if (!componentToMove) {
            console.warn(`[DropMoveOnCanvas] Component ${movedComponentId} not found!`);
            return;
        }
        
        // 检查是否组件有父容器，如果有父容器但被拖到外面，需要移出父容器
        const parent = designStore.findParentComponent(designStore.canvasComponents, movedComponentId);
        const isMovingOutOfContainer = parent !== null;
        
        if (isMovingOutOfContainer) {
            console.log(`[DropMoveOnCanvas] Component ${movedComponentId} is being moved out of container ${parent.id} to canvas root`);
        }
        
        // 获取原始位置 (用于比较)
        const originalLeft = parsePx(componentToMove.style?.left);
        const originalTop = parsePx(componentToMove.style?.top);

        // 计算相对于画布根区域的新位置
        const newLeft = dropX - dragData.offsetX;
        const newTop = dropY - dragData.offsetY;
        const snappedLeft = Math.round(newLeft / currentGridSize) * currentGridSize;
        const snappedTop = Math.round(newTop / currentGridSize) * currentGridSize;
        
        console.log(`[DropMoveOnCanvas] Moving ${movedComponentId}. Original: (${originalLeft}, ${originalTop}), Calculated Snapped: (${snappedLeft}, ${snappedTop})`);

        // 当组件从容器移出时，应该总是执行moveComponent，不需要检查位置是否改变
        const newRelativeStyle = {
            left: `${snappedLeft}px`,
            top: `${snappedTop}px`
        };
        
        console.log(`[DropMoveOnCanvas] Calling moveComponent for ${movedComponentId} to canvas root with style:`, newRelativeStyle);
        // 明确设置newParentId为null，表示移动到根
        designStore.moveComponent(movedComponentId, null, newRelativeStyle);

        // 移动后确保选中
        nextTick(() => {
            if (designStore.selectedComponentId !== movedComponentId) {
                console.log(`[DropMoveOnCanvas] Selecting component ${movedComponentId}`);
                designStore.selectComponent(movedComponentId);
            }
        });

    // --- 处理添加新组件 (从左侧面板拖入) --- 
    } else if (dragData.type) {
      console.log(`[DropAddOnCanvas] Adding new component of type: ${dragData.type}`);
      const snappedLeft = Math.round(dropX / currentGridSize) * currentGridSize;
      const snappedTop = Math.round(dropY / currentGridSize) * currentGridSize;
      
      // 准备新组件的基础信息 (ID, 默认值, zIndex 等由 addComponent 处理)
      const newComponentBase: Partial<CanvasComponent> = {
          type: dragData.type,
          props: { ...(dragData.defaultProps || {}) },
          style: { 
              position: 'absolute',
              left: `${snappedLeft}px`,
              top: `${snappedTop}px`,
          },
          // 确保容器类型有 children 数组
          children: (isContainerType(dragData.type)) ? [] : undefined
      };

      // 设置组件尺寸 - 根据组件配置或使用默认值
      const componentName = dragData.name;
      
      // 执行尺寸设置
      setComponentSize(newComponentBase, componentName);

      console.log('[DropAddOnCanvas] New component base data:', newComponentBase);
      
      // **调用 store action 添加组件到画布根部 (parentId 为 null)**
      designStore.addComponent(newComponentBase as CanvasComponent, null);
      
      // ++ 使用 nextTick 延迟选中 ++ 
      nextTick(() => {
          // 假设最后一个组件是刚添加的
          const lastComponentIndex = designStore.canvasComponents.length - 1;
          if (lastComponentIndex >= 0) {
              const newComponentId = designStore.canvasComponents[lastComponentIndex].id;
              console.log(`[DropAddOnCanvas] Selecting new component ${newComponentId} after nextTick`);
              designStore.selectComponent(newComponentId);
          } else {
              console.warn('[DropAddOnCanvas] Cannot find last component to select after add.');
          }
      });

    } else {
      console.warn('[handleDrop-Canvas] Dropped unknown data type:', dragData);
    }

  } catch (error) {
    console.error('[handleDrop-Canvas] Error processing drop event:', error);
  }
};

// --- Resize Handling ---
const resizingState = ref<{
  componentId: string;
  direction: string;
  startX: number;
  startY: number;
  initialRect: DOMRect;
  initialStyle: { left: number; top: number; width: number; height: number };
} | null>(null);
const handleDirections = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];

// 实时尺寸显示
const newWidth = ref(0);
const newHeight = ref(0);

const handleResizeStart = (customEventData: { direction: string; startX: number; startY: number }) => {
  console.log('[CanvasArea handleResizeStart] Received custom data:', customEventData);
  
  if (!designStore.selectedComponent) return;
  const componentId = designStore.selectedComponent.id;
  const componentElement = document.querySelector(`[data-component-id="${componentId}"]`) as HTMLElement;
  if (!componentElement) {
      console.warn(`[handleResizeStart] Component element not found for ${componentId}`);
      return;
  }
  // Remove preventDefault/stopPropagation - they don't belong here with the custom event object
  // event.preventDefault(); 
  // event.stopPropagation(); 

  const initialRect = componentElement.getBoundingClientRect();
  const componentStyle = designStore.selectedComponent.style || {};
  
  // Use data from the custom event object
  resizingState.value = {
    componentId: componentId,
    direction: customEventData.direction, // Use direction from custom data
    startX: customEventData.startX,      // Use startX from custom data
    startY: customEventData.startY,      // Use startY from custom data
    initialRect: initialRect,
    initialStyle: {
      left: parsePx(componentStyle.left),
      top: parsePx(componentStyle.top),
      // Ensure width/height have valid fallback from rect if style is missing/invalid
      width: parsePx(componentStyle.width) || initialRect.width, 
      height: parsePx(componentStyle.height) || initialRect.height
    }
  };
  console.log('[handleResizeStart] Initialized resizingState:', JSON.parse(JSON.stringify(resizingState.value))); // Log the state

  window.addEventListener('mousemove', handleResizing);
  window.addEventListener('mouseup', handleResizeEnd, { once: true });
};

/**
 * 处理鼠标移动事件 (当正在调整大小时)。
 * 计算新的尺寸和位置（如果适用），并更新 store 中的组件样式。
 */
const handleResizing = (event: MouseEvent) => {
  // 确保 resizingState 有值
  if (!resizingState.value) return;

  const { componentId, direction, startX, startY, initialRect, initialStyle } = resizingState.value;
  const component = designStore.findComponentById(designStore.canvasComponents, componentId);
  if (!component) return;

  // 计算鼠标位移
  const dx = event.clientX - startX;
  const dy = event.clientY - startY;

  // 初始化新的样式变量
  let newStyleWidth = initialStyle.width;
  let newStyleHeight = initialStyle.height;
  let newLeft = initialStyle.left;
  let newTop = initialStyle.top;
  const currentGridSize = designStore.gridSize; // 获取当前的 gridSize

  // --- 根据拖拽方向计算新的 width 和 height ---
  // 使用实际的最小尺寸，例如 30px
  const minWidth = 30;
  const minHeight = 30;

  // 根据拖动方向计算新尺寸
  if (direction.includes('e')) {
    newStyleWidth = Math.max(minWidth, initialStyle.width + dx);
  }
  if (direction.includes('w')) {
    const widthChange = Math.min(initialStyle.width - minWidth, dx);
    newStyleWidth = initialStyle.width - widthChange;
    newLeft = initialStyle.left + widthChange;
  }
  if (direction.includes('s')) {
    newStyleHeight = Math.max(minHeight, initialStyle.height + dy);
  }
  if (direction.includes('n')) {
    const heightChange = Math.min(initialStyle.height - minHeight, dy);
    newStyleHeight = initialStyle.height - heightChange;
    newTop = initialStyle.top + heightChange;
  }

  // 应用网格对齐
  newStyleWidth = Math.round(newStyleWidth / currentGridSize) * currentGridSize;
  newStyleHeight = Math.round(newStyleHeight / currentGridSize) * currentGridSize;
  newLeft = Math.round(newLeft / currentGridSize) * currentGridSize;
  newTop = Math.round(newTop / currentGridSize) * currentGridSize;

  // 更新组件样式
  designStore.updateComponentStyle(componentId, {
    left: `${newLeft}px`,
    top: `${newTop}px`,
    width: `${newStyleWidth}px`,
    height: `${newStyleHeight}px`
  });
  
  // 更新实时尺寸值用于显示
  newWidth.value = newStyleWidth;
  newHeight.value = newStyleHeight;
};

const handleResizeEnd = () => {
  if (!resizingState.value) return;
  
  const { componentId } = resizingState.value;
  
  // 获取组件实例
  const component = designStore.findComponentById(designStore.canvasComponents, componentId);
  if (component) {
    // 从DOM获取实际尺寸来校准
    const componentElement = document.querySelector(`[data-component-id="${componentId}"]`) as HTMLElement;
    if (componentElement) {
      const rect = componentElement.getBoundingClientRect();
      console.log(`[handleResizeEnd] Component ${componentId} actual size from DOM: width=${rect.width}px, height=${rect.height}px`);
      
      // 准备重置样式来确保值被刷新
      const currentStyle = { ...component.style };
      const finalStyle: Partial<CanvasComponent['style']> = {};
      
      // 确保宽高值是有效的
      if (!currentStyle.width || currentStyle.width === 'auto') {
        finalStyle.width = `${Math.round(rect.width)}px`;
      }
      
      if (!currentStyle.height || currentStyle.height === 'auto') {
        finalStyle.height = `${Math.round(rect.height)}px`;
      }
      
      // 如果有需要更正的样式，则应用更新
      if (Object.keys(finalStyle).length > 0) {
        console.log(`[handleResizeEnd] Applying final adjustments to component ${componentId}:`, finalStyle);
        designStore.updateComponentStyle(componentId, finalStyle);
      }
      
      // 确保句柄位置与组件实际大小一致
      nextTick(() => {
        console.log(`[handleResizeEnd] Completed resize for component ${componentId}`);
      });
    }
  }
  
  resizingState.value = null;
  window.removeEventListener('mousemove', handleResizing);
};

// Clean up listeners when component is unmounted
onUnmounted(() => {
  window.removeEventListener('mousemove', handleResizing);
  window.removeEventListener('mouseup', handleResizeEnd);
  window.removeEventListener('keydown', handleKeyDown); // Ensure cleanup here as well
});
// --- Resize Handling End ---

// 画布大小调整处理
const canvasResizingState = ref<{
  direction: string;
  startX: number;
  startY: number;
  initialSize: { width: number; height: number };
} | null>(null);

const handleCanvasResizeStart = (customEventData: { direction: string; startX: number; startY: number }) => {
  console.log('[CanvasArea handleCanvasResizeStart] Received custom data:', customEventData);
  
  canvasResizingState.value = {
    direction: customEventData.direction,
    startX: customEventData.startX,
    startY: customEventData.startY,
    initialSize: { ...designStore.canvasSize }
  };
  
  console.log('[handleCanvasResizeStart] Initial canvas size:', canvasResizingState.value.initialSize);
  
  window.addEventListener('mousemove', handleCanvasResizing);
  window.addEventListener('mouseup', handleCanvasResizeEnd, { once: true });
};

const handleCanvasResizing = (event: MouseEvent) => {
  if (!canvasResizingState.value) return;
  
  const { direction, startX, startY, initialSize } = canvasResizingState.value;
  
  // 计算鼠标移动的距离
  const dx = event.clientX - startX;
  const dy = event.clientY - startY;
  
  // 初始化新的尺寸
  let newWidth = initialSize.width;
  let newHeight = initialSize.height;
  
  // 设置最小尺寸限制
  const minWidth = 100;
  const minHeight = 100;
  
  // 根据拖拽方向计算新的尺寸
  if (direction.includes('e')) {
    newWidth = Math.max(minWidth, initialSize.width + dx);
  }
  if (direction.includes('w')) {
    newWidth = Math.max(minWidth, initialSize.width - dx);
  }
  if (direction.includes('s')) {
    newHeight = Math.max(minHeight, initialSize.height + dy);
  }
  if (direction.includes('n')) {
    newHeight = Math.max(minHeight, initialSize.height - dy);
  }
  
  // 应用网格对齐
  const currentGridSize = designStore.gridSize;
  newWidth = Math.round(newWidth / currentGridSize) * currentGridSize;
  newHeight = Math.round(newHeight / currentGridSize) * currentGridSize;
  
  // 更新画布尺寸
  designStore.updateCanvasSize({ width: newWidth, height: newHeight });
};

const handleCanvasResizeEnd = () => {
  console.log('[handleCanvasResizeEnd] Canvas resizing ended');
  
  canvasResizingState.value = null;
  window.removeEventListener('mousemove', handleCanvasResizing);
};

// 可以在这里添加画布缩放、拖拽组件相关的逻辑

// --- 吸附到网格 --- 
const snapToGrid = (value: number): number => {
  return Math.round(value / gridSize.value) * gridSize.value;
};

const selectedComponentHandlesStyle = computed(() => {
  if (!designStore.selectedComponent) return {};
  const component = designStore.selectedComponent;
  if (!component || !component.style) return {};

  // 获取组件在画布中的绝对位置
  const position = getComponentAbsolutePosition(component.id);
  
  // 日志组件ID和获取到的位置
  console.log(`[HandlesStyle Debug] Component ID: ${component.id}`);
  console.log(`[HandlesStyle Debug] Absolute position:`, position);

  // 确保组件有宽度和高度，应用默认值如果没有
  const rawWidth = component.style.width || '100px';
  const rawHeight = component.style.height || '32px';
  console.log(`[HandlesStyle Debug] Raw width: ${rawWidth}, height: ${rawHeight}`);

  // 解析宽度和高度，移除单位
  const width = parsePx(rawWidth);
  const height = parsePx(rawHeight);
  
  console.log(`[HandlesStyle Debug] Parsed width: ${width}, height: ${height}`);
  
  if (!position || isNaN(width) || isNaN(height)) {
    console.warn(`[HandlesStyle Warning] Invalid dimensions or position for component ${component.id}:`, {
      rawWidth, rawHeight, width, height, position
    });
    // 应用默认值
    return {
      top: `0px`,
      left: `0px`,
      width: '100px',
      height: '32px',
      position: 'absolute' as const,
      pointerEvents: 'none' as const,
      zIndex: 1000
    };
  }

  const style = {
    top: `${position.top}px`,
    left: `${position.left}px`,
    width: `${width}px`,
    height: `${height}px`,
    position: 'absolute' as const,
    pointerEvents: 'none' as const,
    zIndex: 1000
  };

  console.log(`[HandlesStyle] Returning final style:`, style);
  return style;
});

// 更新画布样式的函数
const updateCanvasStyle = () => {
  if (canvasContentRef.value) {
    const { width, height } = designStore.canvasSize;
    canvasContentRef.value.style.width = `${width}px`;
    canvasContentRef.value.style.height = `${height}px`;
    console.log(`[CanvasArea] 更新画布尺寸: ${width}x${height}`);
  }
};

// 画布选择函数
const selectCanvas = (event) => {
    event.stopPropagation();
    console.log('[CanvasArea] 画布被选中');
    
    // 使用特殊 ID 'canvas' 表示选中了画布本身
    designStore.selectComponent('canvas');
    
    // 获取画布元素，确保样式已应用
    if (canvasContentRef.value) {
        // 确保画布有基本样式
        canvasContentRef.value.style.backgroundColor = canvasContentRef.value.style.backgroundColor || '#ffffff';
        canvasContentRef.value.style.borderRadius = canvasContentRef.value.style.borderRadius || '4px';
        canvasContentRef.value.style.border = canvasContentRef.value.style.border || '1px solid #cccccc';
        canvasContentRef.value.style.boxShadow = canvasContentRef.value.style.boxShadow || '0 4px 12px rgba(0, 0, 0, 0.1)';
        console.log('[CanvasArea selectCanvas] 确保画布样式已应用');
    }
};

// 添加判断选中组件是否为交互型组件的计算属性
const isSelectedComponentInteractive = computed(() => {
  if (!designStore.selectedComponent) return false;
  
  const interactiveTypes = [
    'el-button', 
    'el-input', 
    'el-radio', 
    'el-checkbox', 
    'el-select', 
    'el-switch',
    'el-slider',
    'el-color-picker',
    'el-date-picker',
    'el-time-picker',
    'el-rate',
    'el-table',
    'button'
  ];
  
  return interactiveTypes.includes(designStore.selectedComponent.type);
});

// 计算选中组件的尺寸信息，用于显示在调整手柄中
const selectedComponentSize = computed(() => {
  if (!designStore.selectedComponent) return { width: 0, height: 0 };
  
  const style = designStore.selectedComponent.style || {};
  return {
    width: parsePx(style.width as string) || 0,
    height: parsePx(style.height as string) || 0
  };
});

// 提供给ResizeHandle组件的值
provide('resizingState', resizingState);
provide('selectedComponentSize', selectedComponentSize);

</script>

<style scoped>
.canvas-container {
  width: 100%;
  height: 100%;
  overflow: auto; /* 如果内部内容超出，允许滚动 */
  position: relative;
  background-color: #f0f2f5; /* 使用 App.vue 中定义的背景色 */
  display: flex;
  justify-content: flex-start; /* 水平左对齐 */
  align-items: flex-start; /* 垂直顶部对齐 */
  padding: 20px;
}

.canvas-container.grid-visible {
  /* 使用 background-image 实现网格 */
  background-image: linear-gradient(to right, #e0e0e0 1px, transparent 1px),
                    linear-gradient(to bottom, #e0e0e0 1px, transparent 1px);
  /* 使用 designStore.gridSize 设置网格大小 */
  background-size: v-bind("gridSize + 'px'") v-bind("gridSize + 'px'"); 
  background-position: -1px -1px; 
}

.canvas-content {
  margin: 5px;
  /* 这个内部 div 用于放置实际的组件 */
  position: relative;
  /* 使用 designStore.canvasSize */
  /* width 和 height 由 JavaScript 动态设置 */
  background-color: #ffffff; /* 内容区域使用白色背景 */
  border: 1px solid #cccccc; /* 实线边框 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  overflow: visible; /* Changed from hidden to allow handles outside */
  flex-shrink: 0; /* 防止内容区域被压缩 */
  border-radius: 4px; /* 圆角效果 */
}

.canvas-content.selected {
  outline: 2px solid #409eff; /* 被选中时的高亮边框 */
}

.canvas-content p {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #c0c4cc;
  font-size: 14px;
  pointer-events: none; /* 防止干扰 drop 事件 */
}

/* Style for selected component - applied to DynamicRenderer */
:deep(.rendered-component.selected) {
  outline: 1px solid #409eff; /* Restore outline */
  /* background-color: rgba(64, 158, 255, 0.2) !important; */ /* Remove background color */
}

/* Container for resize handles (positioned relative to the selected component) */
.resize-handles-container {
    /* Styles applied via :style binding in template */
    position: absolute; /* Ensure it has position context */
    pointer-events: none; /* 让鼠标事件穿透此容器 */
}

/* 画布调整大小的句柄容器 */
.canvas-resize-handles-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
}

/* 
   移除之前添加的、无效的覆盖规则
.canvas-content > .rendered-component.el-button + .rendered-component.el-button {
    margin-left: 0;
}
*/

/* 尺寸指示器样式 */
.size-indicator {
  position: fixed;
  background-color: #409eff;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  pointer-events: none;
  z-index: 2000;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  top: 10px;
  right: 10px;
  font-weight: bold;
  opacity: 0.9;
  white-space: nowrap;
}

.canvas-size-indicator {
  background-color: #67c23a;
}

</style> 